import 'package:flutter/material.dart';
import '../../utils/G.dart';
import 'package:provider/provider.dart';
import '../../providers/user_provider.dart';
import 'package:badges/badges.dart';

class Mine extends StatefulWidget {
  const Mine({Key? key}) : super(key: key);

  @override
  _MineState createState() => _MineState();
}

class _MineState extends State<Mine> {
  double iconSize = 16;
  Map user = {};

  // 声明样式
  TextStyle h1 = const TextStyle(fontSize: 24);
  TextStyle h2 = TextStyle(fontSize: 14, color: Colors.grey.shade600);

  // 垂直分割线
  SizedBox vline = SizedBox(
    width: 1,
    height: 60,
    child: DecoratedBox(decoration: BoxDecoration(color: Colors.grey.shade300)),
  );

  var _futureInstance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _futureInstance = G.api.user.getInfo();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _futureInstance,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var res = snapshot.data as Map;
            if (res['status'] == 200) {
              user = res['data'];

              // 将用户信息设置到状态中
              context.read<UserProvider>().setUser(user);

              return Container(
                padding: const EdgeInsets.all(10),
                alignment: Alignment.topLeft,
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                  physics: const BouncingScrollPhysics(),
                  child: Column(
                    children: [
                      // 头部菜单
                      _renderUserHeader(),

                      // 用户菜单
                      _renderUserMenu(),

                      // 订单菜单
                      _renderOrderMenu(),

                      // 列表菜单
                      _renderListMenu()
                    ],
                  ),
                ),
              );
            } else {
              // 接口请求失败，跳转到登录页
              context.read<UserProvider>().doLogout();
              // 跳转到登录页
              Future.delayed(const Duration(milliseconds: 500), () {
                G.router.navigateTo(context, '/login');
              });
            }
          } else if (snapshot.hasError) {
            return Center(
              child: Text("${snapshot.error}"),
            );
          }

          return G.loader();
        });
  }

  Widget _renderListMenu() {
    return Column(
      children: [
        ListTile(
            leading: Icon(Icons.room_outlined, size: iconSize),
            title: Text('收获地址'),
            // title: Text(G.t('address')),
            trailing: Icon(Icons.arrow_forward_ios, size: iconSize),
            onTap: () {
              // 跳转到用户收获地址页面
              G.router.navigateTo(context, '/address');
            }),
        ListTile(
            leading: Icon(Icons.room_outlined, size: iconSize),
            title: const Text('注册'),
            trailing: Icon(Icons.arrow_forward_ios, size: iconSize),
            onTap: () {
              G.router.navigateTo(context, '/register');
            }),
        ListTile(
            leading: Icon(Icons.room_outlined, size: iconSize),
            title: const Text('登录'),
            trailing: Icon(Icons.arrow_forward_ios, size: iconSize),
            onTap: () {
              // 跳转到登录页面
              G.router.navigateTo(context, '/login');
            }),
        ListTile(
            leading: Icon(Icons.login_outlined, size: iconSize),
            title: Text('退出'),
            // title: Text(G.t('logout')),
            trailing: Icon(Icons.arrow_forward_ios, size: iconSize),
            onTap: () async {
              var res = await G.api.user.logout();
              if (res['status'] == 200) {
                // 跳转到用户收获地址页面
                context.read<UserProvider>().doLogout();

                // 跳转到登录页
                G.router.navigateTo(context, '/login');
              } else {
                G.error('退出报错');
              }
            }),
      ],
    );
  }

  Widget _renderUserHeader() {
    return Card(
        margin: const EdgeInsets.all(1),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: Container(
            child: ListTile(
                leading: CircleAvatar(
                  radius: 30,
                  backgroundImage: NetworkImage(user['avatar'], scale: 1),
                ),
                title: Text(user['nickname'].toString()),
                subtitle: Text(user['phone'].toString()),
                trailing: const Icon(Icons.settings, size: 26),
                onTap: () {
                  // 点击进入用户编辑页面
                  G.router.navigateTo(context, '/profile');
                })));
  }

  Widget _renderUserMenu() {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 10),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
          side: BorderSide(color: Colors.grey.shade200, width: 1)),
      child: Container(
        margin: const EdgeInsets.all(5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Column(
              children: [
                Text(user['collectCount'].toString(), style: h1),
                InkWell(
                    onTap: () {
                      // 跳转到收藏列表页
                      G.router.navigateTo(context, '/favorite');
                    },
                    child: Text('收藏', style: h2))
              ],
            ),
            vline,
            Column(
              children: [
                Text(user['integral'].toString(), style: h1),
                InkWell(
                    onTap: () {
                      // 跳转到积分列表页
                      G.router.navigateTo(context, '/score');
                    },
                    child: Text('积分', style: h2))
              ],
            ),
            vline,
            Column(
              children: [
                Text(user['couponCount'].toString(), style: h1),
                InkWell(
                    onTap: () {
                      // 跳转到优惠券列表页
                      G.router.navigateTo(context, '/coupon');
                    },
                    child: Text('优惠券', style: h2))
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _renderOrderMenu() {
    return Card(
        margin: const EdgeInsets.all(2),
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
            side: BorderSide(color: Colors.grey.shade200, width: 1)),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text('订单中心'),
                  InkWell(
                      child: Text('查看全部',
                          style: TextStyle(
                              fontSize: 14,
                              color: Theme.of(context).primaryColor)),
                      onTap: () {
                        // 点击进入订单列表页
                        Map<String, dynamic> p = {'type': 1};
                        G.router.navigateTo(
                            context, '/order_list' + G.parseQuery(params: p));
                      })
                ],
              ),
            ),
            const Divider(),
            Container(
              margin: const EdgeInsets.all(5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Column(
                    children: [
                      user['orderStatusNum']['unpaid_count'] != '0'
                          ? Badge(
                              badgeContent: Text(
                                  user['orderStatusNum']['unpaid_count']
                                      .toString(),
                                  style: const TextStyle(color: Colors.white)),
                              child: const Icon(Icons.payment, size: 30))
                          : const Icon(Icons.payment, size: 30),
                      Text('待付款', style: h2)
                    ],
                  ),
                  Column(
                    children: [
                      user['orderStatusNum']['unshipped_count'] != '0'
                          ? Badge(
                              badgeContent: Text(
                                  user['orderStatusNum']['unshipped_count']
                                      .toString(),
                                  style: const TextStyle(color: Colors.white)),
                              child: const Icon(Icons.payment, size: 30))
                          : const Icon(Icons.add_box_outlined, size: 30),
                      Text('待发货', style: h2)
                    ],
                  ),
                  Column(
                    children: [
                      user['orderStatusNum']['received_count'] != '0'
                          ? Badge(
                              badgeContent: Text(
                                  user['orderStatusNum']['received_count']
                                      .toString(),
                                  style: const TextStyle(color: Colors.white)),
                              child: const Icon(Icons.payment, size: 30))
                          : const Icon(Icons.inbox_outlined, size: 30),
                      Text('待收货', style: h2)
                    ],
                  ),
                  Column(
                    children: [
                      user['orderStatusNum']['evaluated_count'] != '0'
                          ? Badge(
                              badgeContent: Text(
                                  user['orderStatusNum']['evaluated_count']
                                      .toString(),
                                  style: const TextStyle(color: Colors.white)),
                              child: const Icon(Icons.payment, size: 30))
                          : const Icon(Icons.comment_outlined, size: 30),
                      Text('待评价', style: h2)
                    ],
                  ),
                  Column(
                    children: [
                      user['orderStatusNum']['refund_count'] != '0'
                          ? Badge(
                              badgeContent: Text(
                                  user['orderStatusNum']['refund_count']
                                      .toString(),
                                  style: const TextStyle(color: Colors.white)),
                              child: const Icon(Icons.payment, size: 30))
                          : const Icon(Icons.refresh_rounded, size: 30),
                      Text('售后|退款', style: h2)
                    ],
                  )
                ],
              ),
            )
          ],
        ));
  }
}
